package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsConstants;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SmsHelper {

    @Autowired
    private IAcsClient client;

    @Autowired
    private SmsProperties smsProp;

    public void sendCode(String phone, String code){
        log.info("【阿里云SMS短信】发短信工具类开始执行！");
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsProp.getDomain());
        request.setSysVersion(smsProp.getVersion());
        request.setSysAction(smsProp.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_REGION_ID, smsProp.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, smsProp.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, smsProp.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\""+smsProp.getCode()+"\":\""+code+"\"}");
        try {
            //发送短信
            CommonResponse response = client.getCommonResponse(request);
            //讲字符串格式的返回值转Json对象
            Map<String, String> resp = JsonUtils.toMap(response.getData(), String.class, String.class);
            //判断返回结果的状态码
            if(StringUtils.equals(resp.get(SmsConstants.SMS_RESPONSE_KEY_CODE), SmsConstants.OK)){
                log.info("【阿里云SMS短信】发送成功，手机用户{}已经接收到了短信验证码！", phone);
                return;
            }
            log.error("【阿里云SMS短信】发送失败！失败原因为：{}", resp.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
        } catch (ServerException e) {
            log.error("【阿里云SMS短信】发送失败！阿里云服务器异常！失败原因为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        } catch (ClientException e) {
            log.error("【阿里云SMS短信】发送失败！乐优短信微服务异常！失败原因为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        }
    }

}
